<?php

/**
 * @author blog.anchen8.net
 * @copyright 2014
 */
class hotel extends actionAbstract {

    /**
     * 构造函数
     * @var array
     */
    function __construct() {
        parent::__construct();
        $this->partnerInfo = $this->userinfo = acl::checkLogin('PmsCookie', '/index.php/partner/common/login');
        if($this->partnerInfo['parentid']!=0){
        	$this->partnerInfo['id'] = $this->partnerInfo['parentid'];
        }
    }

    function hotelziduan($ziduan) {
        $this->loadModel('hotel', 'category');
        $re = $this->hotel->categoryModel->fetchRow("select $ziduan from hotel_category where id=".(isset($_SESSION['hotel_id'])?$_SESSION['hotel_id']:0)." and partnerid=".$this->partnerInfo['id']);
        if($re){
        	return $re[$ziduan];
        }else{
        	return 0;
        }
    }
    
    //房型管理
    function type() {
        $leftpost = "hotel";
        $leftbot = "type";

        $this->loadHelper('extend');
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/type");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $this->loadModel('hotel', 'category');
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'picture');

        $hotel = $this->hotelziduan("status");
        if (empty($hotel)) {
            ajaxReturn('back', "本酒店不存在！", 0);exit;
        }/* elseif (!empty($hotel) && $hotel != 1) {
            ajaxReturn('back', "本酒店冻结中！", 0);
            exit;
        }*/

        $hotelId = $this->hotelziduan("id");
        $where = "categoryid=$hotelId and parentTypeId=0";
        $name = isset($_GET['name']) ? $_GET['name'] : '';
        if (!empty($name)) {
            $where.=" and (title like'%" . $name . "%' or bed like'%" . $name . "%')";
        }
        $re = $this->hotel->typeModel->fetchAll("select * from hotel_type where ".$where);
        if($re){
            foreach($re as $k=>$v){
                $re[$k]['pictureNum']=0;
                $pic_tu=$this->hotel->pictureModel->fetchRow("select count(id) as pictureNum from hotel_picture where hotelId=$hotelId and typeid=".$v['id']);
                if($pic_tu){
                    $re[$k]['pictureNum']=$pic_tu['pictureNum'];
                }
            }
        }
        
        
        include $this->loadWidget('partnerTheme');
    }

    //房型修改、添加
    function typeEdit() {
        global $pmsconfigs;
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/typeEdit");
        if(!$str_return){
        	exit(json_encode(array('state' => 0, 'html' => '没有该权限！')));
        }
        $this->loadModel('hotel', 'type');
        $hotelId = $this->hotelziduan('id');

        $id = isset($_POST['id']) ? (int) ($_POST['id']) : 0;
        $data['title'] = isset($_POST['title']) ? $_POST['title'] : '';
        $data['bed'] = isset($_POST['bed']) ? $_POST['bed'] : '';
        $data['floor'] = isset($_POST['floor']) ? $_POST['floor'] : '';
        $data['area'] = isset($_POST['area']) ? $_POST['area'] : '';
        $data['maxnumber'] = isset($_POST['maxnumber']) ? (int) ($_POST['maxnumber']) : 0;
        $data['price'] = isset($_POST['price']) ? (int) ($_POST['price']) : 0;
        $data['categoryid'] = $hotelId;
        $data['status'] = 1;
		
        if ($id > 0) {
            $isup = $this->hotel->typeModel->fetchRow("select id from hotel_type where id!=$id and title='" . $data['title'] . "' and categoryid=" . $data['categoryid']);
            if ($isup) {
                exit(json_encode(array('state' => 0, 'html' => '该房型已存在！')));
            } else {
                $isre = $this->hotel->typeModel->update($data, "id=$id and categoryid=$hotelId");
                if ($isre) {
                    $this->loadModel('hotel', 'price');
					$sql="select * from hotel_price where hotelId=$hotelId and parentTypeId=$id and isdetailed=0";
                    $res_price = $this->hotel->priceModel->fetchAll($sql);
                    foreach ($res_price as $k => $v) {
                        $data_price = array();
                        $data_price['sellPrice'] = $data['price'] * $pmsconfigs['zhekou'][$v['rebate']] / 10;
                        $this->hotel->priceModel->update($data_price, "id=".$v['id']);
                    }
                }
            }
        } else {
            $isadd = $this->hotel->typeModel->fetchRow("select * from hotel_type where title='" . $data['title'] . "' and categoryid=" . $data['categoryid']);
            if ($isadd) {
                exit(json_encode(array('state' => 0, 'html' => '该房型已存在！')));
            } else {
                $isre = $this->hotel->typeModel->insert($data);
            }
        }
        if ($isre) {

            /**
             * 添加、修改子房型名称
             */
            $zidata = array();
            for ($i = 1; $i <= 8; $i++) {
                $zidata[$i]['parentTypeId'] = $isre;
                if ($id > 0) {
                    $zidata[$i]['parentTypeId'] = $id;
                }
                $zidata[$i]['bed'] = $data['bed'];
                $zidata[$i]['floor'] = $data['floor'];
                $zidata[$i]['area'] = $data['area'];
                $zidata[$i]['maxnumber'] = $data['maxnumber'];
                $zidata[$i]['price'] = $data['price'];
                $zidata[$i]['categoryid'] = $hotelId;
                $zidata[$i]['status'] = 1;
                if ($i == 1) {
                    $zidata[$i]['title'] = $data['title'] . "(含早)";
                    $zidata[$i]['zisort'] = 1;
                } elseif ($i == 2) {
                    $zidata[$i]['title'] = $data['title'] . "(不含早)";
                    $zidata[$i]['zisort'] = 2;
                } elseif ($i == 3) {
                    $zidata[$i]['title'] = $data['title'] . "(提前1天以上预订)";
                    $zidata[$i]['zisort'] = 3;
                } elseif ($i == 4) {
                    $zidata[$i]['title'] = $data['title'] . "(连续1天以上入住)";
                    $zidata[$i]['zisort'] = 4;
                } elseif ($i == 5) {
                    $zidata[$i]['title'] = $data['title'] . "(含早)(现付)";
                    $zidata[$i]['zisort'] = 5;
                } elseif ($i == 6) {
                    $zidata[$i]['title'] = $data['title'] . "(不含早)(现付)";
                    $zidata[$i]['zisort'] = 6;
                } elseif ($i == 7) {
                    $zidata[$i]['title'] = $data['title'] . "(提前1天以上预订)(现付)";
                    $zidata[$i]['zisort'] = 7;
                } elseif ($i == 8) {
                    $zidata[$i]['title'] = $data['title'] . "(连续1天以上入住)(现付)";
                    $zidata[$i]['zisort'] = 8;
                }
            }
            if ($id > 0) {
                foreach ($zidata as $k => $v) {
                    $this->hotel->typeModel->update($v, " parentTypeId=$id and zisort=" . $v['zisort']);
                }
            } else {
                foreach ($zidata as $k => $v) {
                    $this->hotel->typeModel->insert($v);
                }
            }
			//echo "<pre>";print_r($zidata);exit;
            /**
             * 传输给OSII
             */
            $this->loadApi('osiiHotel');
            $osiiHotel = new osiiHotel();

            $body = array();
            $i = 0;
            foreach ($zidata as $k => $v) {
                $body[$i]['hotelCode'] = $hotelId;
                $body[$i]['roomTypeCode'] = ($id > 0 ? ($id + $i + 1) : ($isre + $i + 1));
                $body[$i]['roomName'] = $v['title'];
                $body[$i]['areaRange'] = $v['area'];
                $body[$i]['floorRange'] = $v['floor'];
                $body[$i]['roomDesc'] = "";
                $body[$i]['person'] = $v['maxnumber'];
                $body[$i]['addBed'] = 0;
                $body[$i]['addBedFee'] = 0;
                $body[$i]['roomQuantity'] = 0;
                $body[$i]['currency'] = "RMB";
                $body[$i]['noSmoking'] = 0;
                $body[$i]['window'] = 0;
                $body[$i]['children'] = 0;
                $body[$i]['hasBroadNet'] = "";
                $body[$i]['hasWirelessBroadnet'] = "";
                $body[$i]['wiredBroadnetRoom'] = 0;
                $body[$i]['wirelessBroadnetRoom'] = 0;
                $body[$i]['bedTypeID'] = 0;
                $body[$i]['bedTypeName'] = $v['bed'];
                $i++;
            }
            $reosii = $osiiHotel->types($body);
            exit(json_encode(array('state' => 1, 'html' => '操作成功！')));
        }
        exit(json_encode(array('state' => 0, 'html' => '操作失败！')));
    }

    //房型删除
    function typeDel() {
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/typeDel");
        if(!$str_return){
        	exit(json_encode(array('state' => 0, 'html' => '没有该权限！')));
        }
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'info');
        $this->loadModel('pms', 'orders');
        $hotelId = $this->hotelziduan('id');

        $id = isset($_POST['id']) ? (int) ($_POST['id']) : 0;

        $zi_types = $this->hotel->typeModel->fetchAll("select id from hotel_type where categoryid=$hotelId and parentTypeId=$id");
        $zi_types_all = "";
        if ($zi_types) {
            foreach ($zi_types as $k => $v) {
                if ($k == 0) {
                    $zi_types_all.=$v['id'];
                } else {
                    $zi_types_all.=',' . $v['id'];
                }
            }
        }

        $sql = "select id from pms_orders where hotelId=$hotelId and roomId in($zi_types_all) and startDate>=" . strtotime(date('Y-m-d', time()));
        $re = $this->pms->ordersModel->fetchRow($sql);
        if ($re) {
            exit(json_encode(array('state' => 0, 'html' => '该房型正在使用中，不能删除！')));
        } else {

            $fu_type = $this->hotel->typeModel->fetchRow("select a.*,b.hotelName from hotel_type as a left join hotel_category as b on b.id=a.categoryid where a.categoryid=$hotelId and a.id=$id");

            //删除操作
            $isre = $this->hotel->typeModel->delete($id);
            if ($isre) {
                foreach ($zi_types as $k => $v) {
                    $this->hotel->typeModel->delete($v['id']);
                }
                exit(json_encode(array('state' => 1, 'html' => '操作成功！')));
            } else {
                exit(json_encode(array('state' => 0, 'html' => '操作失败！')));
            }
        }
        exit(json_encode(array('state' => 0, 'html' => '操作失败！')));
    }

    //房量管理
    function room() {
    	$this->loadHelper('extend');
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/room");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $leftpost = "hotel";
        $leftbot = "room";
        $this->loadModel('hotel', 'type');

        $hotelId = $this->hotelziduan("id");
        $types = $this->hotel->typeModel->fetchAll("select * from hotel_type where status=1 and categoryid=$hotelId and parentTypeId=0");
        
        include $this->loadWidget('partnerTheme');
    }

    //房量修改
    function roomEdit() {
    	$this->loadHelper('extend');
    	$str_return = $this->my_authority("hotel/roomEdit");
    	if(!$str_return){
    		ajaxReturn('', "没有该权限！", 0);exit;
    	}
        $hotelId = $this->hotelziduan('id');
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'countrooms');

        if ($_POST) {
            $check_th_all = isset($_POST['check_th_all']) ? $_POST['check_th_all'] : '';
            $roomNum = isset($_POST['roomNum']) ? $_POST['roomNum'] : '';
            if ($check_th_all) {
                if ($roomNum) {
                    foreach ($roomNum as $k => $v) {
                        if (array_key_exists($k, $check_th_all) == false) {
                            unset($roomNum[$k]);
                        }
                    }
                }
            } else {
                $roomNum = array();
            }
            if ($roomNum) {
                foreach ($roomNum as $k => $v) {
                    $data = array();
                    $data['roomNum'] = (int) ($v);
                    $sql = "select a.alreadyRoom,b.title from hotel_countrooms as a left join hotel_type as b on b.id=a.typeId";
                    $sql.=" where a.hotelId=$hotelId and a.typeId=$k and a.created>='" . strtotime(date('Y-m-d', time())) . "' order by a.alreadyRoom desc";

                    $re = $this->hotel->countroomsModel->fetchRow($sql);
                    if ($re && $data['roomNum'] < $re['alreadyRoom']) {
                        ajaxReturn('', $re['title'] . "：不能低于使用中的房间数，已使用 ".$re['alreadyRoom']." 间", 0);exit;
                    }
                    $this->hotel->typeModel->update($data, "categoryid=$hotelId and id=$k");
                }
                ajaxReturn('refurbish', "操作成功！", 1);exit;
            }
            ajaxReturn('', "请勾选要保存的房型！", 0);exit;
        }
    }

    //房态管理
    function info() {
        global $pmsconfigs;
        $this->loadHelper('extend');
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/info");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $leftpost = "hotel";
        $leftbot = "info";

        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'typestatus');
        $this->loadModel('pms', 'orders');
        $this->loadModel('pms', 'channels');
        $this->loadModel('hotel', 'countrooms');
        $hotelId = $this->hotelziduan('id');
        //房型
		$typeSql="SELECT a.*,SUM(b.alreadyRoom) AS alreadyRoom FROM hotel_type AS a ";
		$typeSql.=" LEFT JOIN hotel_countrooms AS b ON a.id=b.typeId ";
		$typeSql.=" WHERE a.categoryid=$hotelId AND a.parentTypeId = 0 GROUP BY a.id";
        $infoParent = $this->hotel->typeModel->fetchAll($typeSql);

        //房间内容、房型名称
        if($this->partnerInfo['isbusiness']==1){
        	$sqlRoom = "SELECT * FROM hotel_type WHERE categoryid=$hotelId AND parentTypeId != 0";
			$sqlRoom.=" and zisort<=4";
        }elseif ($this->partnerInfo['isbusiness']==2){
        	$sqlRoom = "SELECT * FROM hotel_type WHERE categoryid=$hotelId AND parentTypeId != 0";
			$sqlRoom.=" and zisort!=3 and zisort!=4 and zisort!=7 and zisort!=8";
        }
        $rooms = $this->hotel->typeModel->fetchAll($sqlRoom." order by zisort asc");

        $sqlCount = 'SELECT *,SUM(alreadyRoom) as total  FROM hotel_countrooms GROUP BY typeId,created';
        $roomTotal = $this->hotel->countroomsModel->fetchAll($sqlCount);
        //echo '<pre>';print_r($roomTotal);

        $statime = isset($_GET['statime']) ? strtotime($_GET['statime']) : strtotime(date('Y-m-d', time()));
        if ($statime <= strtotime(date('Y-m-d', time()))) {
            $statime = strtotime(date('Y-m-d', time()));
        }
        $times = array(); //时间列表
        $infostatus = array(); //房态列表
        if (!empty($statime)) {
            for ($i = 0; $i < 10; $i++) {
                $fotimes = $statime + $i * 24 * 3600; //时间戳
                $wday = getdate($fotimes); //时间的 详细
                $times[$i]['date'] = date('m', $fotimes) . '-' . date('d', $fotimes); //时间
                $times[$i]['time'] = $fotimes; //时间戳
                $times[$i]['wday'] = $wday['wday']; //星期
                //房态信息array();//
                $sql = "select a.*,b.name,b.type from hotel_typestatus as a left join pms_orders as b ";
                $sql.=" on a.hotelId=b.hotelId AND a.typeId=b.roomId AND (a.times=b.startDate OR a.times>b.startDate)";
				$sql.=" AND a.times<b.endDate WHERE a.times=$fotimes  and a.hotelId=$hotelId";
                $infostatus[$i] = $this->hotel->typestatusModel->fetchAll($sql);
            }
        }
        //echo '<pre>';print_r($infostatus);exit;
        $roomstatus = array(); //房态列表  变一维数组
        $i = 0;
        foreach ($infostatus as $k => $v) {
            if (!empty($v)) {
                foreach ($v as $key => $val) {
                    $roomstatus[$i] = $val;
                    $i++;
                }
            }
        }
        //echo '<pre>';print_r($infostatus);exit;
		
        include $this->loadWidget('partnerTheme');
    }

    //单一房态修改
    function infoStatus() {
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/infoStatus");
        if(!$str_return){
        	ajaxReturn('', "没有该权限！", 0);exit;
        }
        $this->loadModel('hotel', 'info');
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'typestatus');
        $this->loadModel('hotel', 'countrooms');
        $hotelId = $this->hotelziduan('id');
        $typeid = isset($_POST['typeid']) ? (int) ($_POST['typeid']) : 0; //房型id
        $parentTypeId = isset($_POST['parentTypeId']) ? (int) ($_POST['parentTypeId']) : 0;
        $status = isset($_POST['status']) ? (int) ($_POST['status']) : '';
        $statime = isset($_POST['statime']) ? strtotime($_POST['statime']) : '';
        $endtime = isset($_POST['endtime']) ? strtotime($_POST['endtime']) : '';
        $lateReserveTime=isset($_POST['lateReserveTime'])?(int)($_POST['lateReserveTime']):0;
        $payType=isset($_POST['payType'])?$_POST['payType']:'PP';
        $guarantee=isset($_POST['guarantee'])?$_POST['guarantee']:'2-F';
        $lateCancelTime=isset($_POST['lateCancelTime'])?$_POST['lateCancelTime']:0;
        
		$typePay=$this->hotel->typeModel->fetchRow("select zisort from hotel_type where id=$typeid and categoryid=$hotelId and parentTypeId=$parentTypeId");
		if($typePay&&$typePay['zisort']>=5&&$typePay['zisort']<=8){
			$payType="FG";
		}else{
			$payType="PP";
		}
		
        if (empty($statime)) {
            ajaxReturn('', '起始时间不能为空！', 0);exit;
        }
        if (!empty($endtime) && $statime > $endtime) {
            ajaxReturn('', '起始时间不能大于结束时间！', 0);exit;
        }
        if (empty($typeid)) {
            ajaxReturn('', '操作失败！', 0);exit;
        }
        
        //批量修改
        if (!empty($endtime) && (($endtime - $statime) / 24 / 3600) > 0) {
            $day = ($endtime - $statime) / 24 / 3600;
            for ($i = 0; $i <= $day; $i++) {
                $times = $statime + $i * 24 * 3600;
                $all = $this->hotel->typestatusModel->fetchRow("select * from hotel_typestatus where hotelId=$hotelId and typeid=$typeid and times=$times");
                if (empty($all)) {
                    $tarr['hotelId'] = $hotelId;
                    $tarr['status'] = $status;
                    $tarr['typeid'] = $typeid;
                    $tarr['times'] = $times;
                    $tarr['parentTypeId'] = $parentTypeId;
                    $tarr['payType']=$payType;
                    $tarr['guarantee']=$guarantee;
                    $tarr['lateCancelTime']=$lateCancelTime;
					$tarr['lateReserveTime']=$lateReserveTime;
                    $re = $this->hotel->typestatusModel->insert($tarr);
                } else {
                    if ($all['status'] != 3 && $all['status'] != 4) {
                        $qrr['status'] = $status;
                        $qrr['payType'] = $payType;
						$qrr['guarantee']=$guarantee;
						$qrr['lateCancelTime']=$lateCancelTime;
						$qrr['lateReserveTime']=$lateReserveTime;
                        $qrr['created']= date('Y-m-d H:i:s',time());
                        $re = $this->hotel->typestatusModel->update($qrr, $all['id']);
                    }
                }
            }
        } else {//单一时间修改
            $day = 0;
            $endtime = $statime;
            $onesql = "select * from hotel_typestatus where hotelId='$hotelId' and typeid=$typeid and times=$statime";
            $one = $this->hotel->typestatusModel->fetchRow($onesql);
            if ($one) {
                if ($one['status'] == 3 || $one['status'] == 4) {
                    ajaxReturn('', "该时间段-的房间不能修改！", 0);exit;
                }
                $data['status'] = $status;
                $data['payType'] = $payType;
				$data['guarantee']=$guarantee;
				$data['lateCancelTime']=$lateCancelTime;
				$data['lateReserveTime']=$lateReserveTime;
                $data['created']= date('Y-m-d H:i:s',time());
                $re = $this->hotel->typestatusModel->update($data, $one['id']);
            } else {
                $arr['hotelId'] = $hotelId;
                $arr['times'] = $statime;
                $arr['status'] = $status;
                $arr['typeid'] = $typeid;
                $arr['parentTypeId'] = $parentTypeId;
                $arr['payType'] = $payType;
				$arr['guarantee']=$guarantee;
				$arr['lateCancelTime']=$lateCancelTime;
				$arr['lateReserveTime']=$lateReserveTime;
                $re = $this->hotel->typestatusModel->insert($arr);
            }
        }
        
        //调用接口
        $this->loadApi('osiiHotel');
        $osiiHotel = new osiiHotel();
        
        $roomTypeId = $typeid;
		$hotelGroupHotelCode = $hotelId;
		//设置房态
		$body = array();
		//封装数据
		$body['hotelCode'] = $hotelGroupHotelCode;
		$body['startDate'] = date('Y-m-d', $statime);
		$body['endDate'] = date('Y-m-d', $endtime);
		$body['editer'] = 'uni1001';
		$body['roomID'] = $roomTypeId;
		$typeTotal =  $this->hotel->typeModel->fetchRow("SELECT roomNum FROM hotel_type WHERE id=$parentTypeId");
		
		$userLimited_allNeedGuarantee=explode('-',$guarantee);
        $prepayLCT=$this->partnerInfo['isbusiness']==1?'23988':0;
		for ($d = 0; $d <= $day; $d++) {//总共多少天选择
			$times = $statime + $d * 24 * 3600;
			$sql_total = "SELECT SUM(alreadyRoom) as total FROM hotel_countrooms WHERE hotelId=$hotelId and typeid=$parentTypeId AND created =$times";
			$fl = $this->hotel->countroomsModel->fetchRow($sql_total);
			if ($status == 0) {
				$fl = 0;
			} else {
				$fl = empty($fl['total']) ? $typeTotal['roomNum'] : (($typeTotal['roomNum']-$fl['total'])>0?$typeTotal['roomNum']-$fl['total']:0);
			}
			
			if ($fl == 0) {
				$roomstatus = 'N';
			} else {
				$roomstatus = 'G';
			}
			
			$room_info = array(
				'fl' => $fl,
				'setToDate' =>  date('Y-m-d', $times),
				'changeDefault' => 'T',
				'holdDeadline' => '9999',
				'note' => '',
				'reserveTime' => '0',
				'roomstatus' => $roomstatus,
				'roomsInv' => '0',
				'guarantee' => '',
				'guaranteeLCT' => $lateCancelTime,
				'prepayLCT' => $prepayLCT?$prepayLCT:$lateCancelTime,
				'allNeedGuarantee' => $userLimited_allNeedGuarantee[1],
				'lateReserveTime' => $lateReserveTime,
				'deductType' => 'C',
				'blanceType' => $payType,
				'restorable' => 'T',
				'checkType' => 'C',
				'userLimited'=> $userLimited_allNeedGuarantee[0]
			);
			$body['roomInfoList'][$d] = $room_info;
		}
		//echo '<pre>';print_r($body);exit;
		$arr = $osiiHotel->roomstatus($body);
		ajaxReturn('refurbish', '操作成功！', 1);exit;
    }
    
    //一键设置房态
    function infoStatusAll() {
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/infoStatus");
        if(!$str_return){
        	ajaxReturn('', "没有该权限！", 0);exit;
        }
        $this->loadModel('hotel', 'info');
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'typestatus');
        $this->loadModel('hotel', 'countrooms');
        $hotelId = $this->hotelziduan('id');
        $typeid = isset($_POST['checkbox'])? $_POST['checkbox'] : 0; //房型id
        $status = isset($_POST['status']) ? (int) ($_POST['status']) : '';
        $statime = isset($_POST['statime']) ? strtotime($_POST['statime']) : '';
        $endtime = isset($_POST['endtime']) ? strtotime($_POST['endtime']) : '';
        $lateReserveTime=isset($_POST['lateReserveTime'])?(int)($_POST['lateReserveTime']):0;
        $payType=isset($_POST['payType'])?$_POST['payType']:'PP';
        $guarantee=isset($_POST['guarantee'])?$_POST['guarantee']:'2-F';
        $lateCancelTime=isset($_POST['lateCancelTime'])?$_POST['lateCancelTime']:0;
        
        if (empty($statime)) {
            ajaxReturn('', '起始时间不能为空！', 0);exit;
        }
        if (!empty($endtime) && $statime > $endtime) {
            ajaxReturn('', '起始时间不能大于结束时间！', 0);exit;
        }
        if (empty($typeid)) {
            ajaxReturn('', '请选择房型！', 0);exit;
        }
        
        //批量修改
        if (!empty($endtime) && (($endtime - $statime) / 24 / 3600) > 0) {
            $day = ($endtime - $statime) / 24 / 3600;
            for ($i = 0; $i <= $day; $i++) {
                $times = $statime + $i * 24 * 3600;
                foreach ($typeid as $k=>$v){
                    $all = $this->hotel->typestatusModel->fetchRow("select * from hotel_typestatus where hotelId=$hotelId and typeid=$v and times=$times");
                    $parentTypeId=$this->hotel->typeModel->fetchRow("select parentTypeId,zisort from hotel_type where categoryid=$hotelId and id=$v");
                    if($parentTypeId&&$parentTypeId['zisort']>=5&&$parentTypeId['zisort']<=8){
						$payType="FG";
					}else{
						$payType="PP";
					}
					if (empty($all)) {
                        $tarr['hotelId'] = $hotelId;
                        $tarr['status'] = $status;
                        $tarr['typeid'] = $v;
                        $tarr['times'] = $times;
                        $tarr['parentTypeId'] = $parentTypeId['parentTypeId'];
                        $tarr['payType'] = $payType;
						$tarr['guarantee']=$guarantee;
						$tarr['lateCancelTime']=$lateCancelTime;
						$tarr['lateReserveTime']=$lateReserveTime;
                        $re = $this->hotel->typestatusModel->insert($tarr);
                    } else {
                        if ($all['status'] != 3 && $all['status'] != 4) {
                            $qrr['status'] = $status;
                            $qrr['parentTypeId'] = $parentTypeId['parentTypeId'];
                            $qrr['payType'] = $payType;
							$qrr['guarantee']=$guarantee;
							$qrr['lateCancelTime']=$lateCancelTime;
							$qrr['lateReserveTime']=$lateReserveTime;
                            $qrr['created']= date('Y-m-d H:i:s',time());
                            $re = $this->hotel->typestatusModel->update($qrr, $all['id']);
                        }
                    }
                }
            }
        } else {//单一时间修改
            $day = 0;
            $endtime = $statime;
            foreach ($typeid as $k=>$v){
                $onesql = "select * from hotel_typestatus where hotelId=$hotelId and typeid=$v and times=$statime";
                $one = $this->hotel->typestatusModel->fetchRow($onesql);
                $parentTypeId=$this->hotel->typeModel->fetchRow("select parentTypeId,zisort from hotel_type where categoryid=$hotelId and id=$v");
                if($parentTypeId&&$parentTypeId['zisort']>=5&&$parentTypeId['zisort']<=8){
					$payType="FG";
				}else{
					$payType="PP";
				}
				if ($one) {
                    if ($one['status'] == 3 || $one['status'] == 4) {
                        ajaxReturn('', "该时间段-的房间不能修改！", 0);exit;
                    }
                    $data['status'] = $status;
                    $data['parentTypeId'] = $parentTypeId['parentTypeId'];
                    $data['payType'] = $payType;
					$data['guarantee']=$guarantee;
					$data['lateCancelTime']=$lateCancelTime;
					$data['lateReserveTime']=$lateReserveTime;
                    $data['created']= date('Y-m-d H:i:s',time());
                    $re = $this->hotel->typestatusModel->update($data, $one['id']);
                } else {
                    $arr['hotelId'] = $hotelId;
                    $arr['times'] = $statime;
                    $arr['status'] = $status;
                    $arr['typeid'] = $v;
                    $arr['parentTypeId'] = $parentTypeId['parentTypeId'];
                    $arr['payType'] = $payType;
					$arr['guarantee']=$guarantee;
					$arr['lateCancelTime']=$lateCancelTime;
					$arr['lateReserveTime']=$lateReserveTime;
                    $re = $this->hotel->typestatusModel->insert($arr);
                }
            }
        }
        
        //调用接口
        $this->loadApi('osiiHotel');
        $osiiHotel = new osiiHotel();
        foreach ($typeid as $k=>$val){
			$roomTypeId = $val;
			$hotelGroupHotelCode = $hotelId;
			//设置房态
			$body = array();
			//封装数据
			$body['hotelCode'] = $hotelGroupHotelCode;
			$body['startDate'] = date('Y-m-d', $statime);
			$body['endDate'] = date('Y-m-d', $endtime);
			$body['editer'] = 'uni1001';
			$body['roomID'] = $roomTypeId;
			$typeSon =  $this->hotel->typeModel->fetchRow('SELECT parentTypeId FROM hotel_type WHERE id='.$val);
			$typeTotal =  $this->hotel->typeModel->fetchRow('SELECT roomNum,zisort FROM hotel_type WHERE id='.$typeSon['parentTypeId']);
            if($typeTotal&&$typeTotal['zisort']>=5&&$typeTotal['zisort']<=8){
				$payType="FG";
			}else{
				$payType="PP";
			}
			$userLimited_allNeedGuarantee=explode('-',$guarantee);
            $prepayLCT=$this->partnerInfo['isbusiness']==1?'23988':0;
			for ($d = 0; $d <= $day; $d++) {//总共多少天选择
				$times = $statime + $d * 24 * 3600;
				$sql_total = "SELECT SUM(alreadyRoom) as total FROM hotel_countrooms WHERE hotelId=$hotelId and typeid='".$typeSon['parentTypeId']."' AND created =$times";
				$fl = $this->hotel->countroomsModel->fetchRow($sql_total);
				if ($status == 0) {
					$fl = 0;
				} else {
					$fl = empty($fl['total']) ? $typeTotal['roomNum'] : (($typeTotal['roomNum']-$fl['total'])>0?$typeTotal['roomNum']-$fl['total']:0);
				}

				if ($fl == 0) {
					$roomstatus = 'N';
				} else {
					$roomstatus = 'G';
				}

				$room_info = array(
					'fl' => $fl,
					'setToDate' =>  date('Y-m-d', $times),
					'changeDefault' => 'T',
					'holdDeadline' => '9999',
					'note' => '',
					'reserveTime' => '0',
					'roomstatus' => $roomstatus,
					'roomsInv' => '0',
					'guarantee' => '',
					'guaranteeLCT' => $lateCancelTime,
					'prepayLCT' => $prepayLCT?$prepayLCT:$lateCancelTime,
					'allNeedGuarantee' => $userLimited_allNeedGuarantee[1],
					'lateReserveTime' => $lateReserveTime,
					'deductType' => 'C',
					'blanceType' => $payType,
					'restorable' => 'T',
					'checkType' => 'C',
					'userLimited'=> $userLimited_allNeedGuarantee[0]
				);
				$body['roomInfoList'][$d] = $room_info;
			}
			//echo '<pre>';print_r($body);exit;
			$arr = $osiiHotel->roomstatus($body);
        }
        ajaxReturn('refurbish', '操作成功！', 1);exit;
    }

    //图片管理
    function picture() {
        $leftpost = "hotel";
        $leftbot = "type";
        $this->loadHelper('extend');
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/picture");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'picture');
        $this->loadHelper('pager');
        $hotelId = $this->hotelziduan('id');

        $typeid = isset($_GET['typeid']) ? (int) ($_GET['typeid']) : 0;

        $toptitle = "";
        $result = $this->hotel->typeModel->fetchRow("select * from hotel_type where id=$typeid");
        if ($result) {
            $toptitle = $result['title'];
        }

        $size = 10;
        $page = isset($_GET['page']) ? (int) ($_GET['page']) : 1;
        $offset = ($page - 1) * $size;

        $sql = "select * from hotel_picture where typeid=$typeid and hotelId=$hotelId";
        $reto = $this->hotel->pictureModel->fetchAll($sql);

        $count = count($reto);
        $number = ceil($count / $size);
        $extend = new pager();
        $pageHtml = $extend->outputadmin($number, $page, "", "", $count, $size);
        $re = $this->hotel->pictureModel->fetchAll($sql . " order by id asc limit $offset,$size");
        //$re=$this->hotel->pictureModel->select($selected,$where,'ID asc',$offset,$size);

        include $this->loadWidget('partnerTheme');
    }

    //添加、修改图片
    function pictureEdit() {
        $leftpost = "hotel";
        $leftbot = "type";
        $this->loadHelper('extend');
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/pictureEdit");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $js = new js();
        $this->loadHelper('image');
        $image = new image();
        $this->loadModel('hotel', 'picture');
        $hotelId = $this->hotelziduan('id');

        $id = isset($_GET['id']) ? (int) ($_GET['id']) : 0;
        $typeid = isset($_GET['typeid']) ? (int) ($_GET['typeid']) : 0;

        $re = $this->hotel->pictureModel->fetchRow("select * from hotel_picture where id=$id");

        if ($_POST) {
            $id = isset($_POST['id']) ? (int) ($_POST['id']) : 0;
            $typeid = isset($_POST['typeid']) ? (int) ($_POST['typeid']) : 0;
            $old_img = isset($_POST['old_img']) ? $_POST['old_img'] : '';
            $data['title'] = isset($_POST['title']) ? $_POST['title'] : '';
            $data['typeid'] = $typeid;
            $data['status'] = 0;
            $data['hotelId'] = $hotelId;
            //图片处理
            if (!empty($_FILES['imagefile']['name'])) {
                $return = $image->updImg('imagefile', 600, 400);
                if (is_array($return)) {
                    ajaxReturn('refurbish', $return['text'], 0);exit;
                } else {
                    $data['pcurl'] = $return;
                }
            } else {
                if (empty($old_img)) {
                    ajaxReturn('', '请上传图片！', 0);exit;
                }
            }

            if ($id > 0) {
                $result = $this->hotel->pictureModel->update($data, $id);
            } else {
                $result = $this->hotel->pictureModel->insert($data);
            }
            if ($result) {
                if (isset($data['pcurl'])) {
                    @unlink(ROOT_PATH . $old_img);
                    if (strpos($old_img, '_thumb')) {
                        $old_img_thumb = str_replace('_thumb', '', $old_img);
                        @unlink(ROOT_PATH . $old_img_thumb);
                    }
                }

                ajaxReturn('back', '保存成功！', 1);exit;
            } else {
                ajaxReturn('', '保存失败！', 0);exit;
            }
        }

        include $this->loadWidget('partnerTheme');
    }

    //修改状态
    function pictureStatus() {
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/pictureStatus");
        if(!$str_return){
        	exit(json_encode(array('state' => 0, 'html' => '您没有该权限！')));
        }
        $this->loadModel('hotel', 'picture');
        $id = isset($_POST['id']) ? (int) ($_POST['id']) : 0;
        $resuot = $this->hotel->pictureModel->fetchRow("select * from hotel_picture where id=$id");
        if (!empty($resuot) && $resuot['status'] == 1) {
            $data['status'] = 3;
        } elseif (!empty($resuot) && $resuot['status'] == 3) {
            $data['status'] = 1;
        } else {
            exit(json_encode(array('state' => 0, 'html' => '操作失败！')));
        }
        $re = $this->hotel->pictureModel->update($data, $id);
        if ($re) {
            exit(json_encode(array('state' => 1, 'html' => '操作成功！')));
        } else {
            exit(json_encode(array('state' => 0, 'html' => '操作失败！')));
        }
    }

    //删除图片
    function pictureDel() {
    	$this->loadHelper('extend');
    	$str_return = $this->my_authority("hotel/pictureDel");
    	if(!$str_return){
    		exit(json_encode(array('state' => 0, 'html' => '没有该权限！')));
    	}
        $this->loadModel('hotel', 'picture');
        $id = isset($_POST['id']) ? (int) ($_POST['id']) : 0;
        $resuot = $this->hotel->pictureModel->fetchRow("select pcurl from hotel_picture where id=$id");
        if ($resuot) {
            $re = $this->hotel->pictureModel->delete($id);
            if ($re) {
                $pcurl = $resuot['pcurl'];
                @unlink(ROOT_PATH . $pcurl);
                if (strpos($pcurl, '_thumb')) {
                    $old_img_thumb = str_replace('_thumb', '', $pcurl);
                    @unlink(ROOT_PATH . $old_img_thumb);
                }
                exit(json_encode(array('state' => 1, 'html' => '操作成功！')));
            }
        }
        exit(json_encode(array('state' => 0, 'html' => '操作失败！')));
    }

    //价格管理
    public function price() {
        $leftpost = "hotel";
        $leftbot = "price";
        $this->loadHelper('extend');
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/price");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        global $pmsconfigs;
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'price');
        $this->loadModel('pms','channels');
        $this->loadModel('pms','chstatus');
        $hotelId = $this->hotelziduan('id');

        $types = $this->hotel->typeModel->fetchAll("select * from hotel_type where status=1 and categoryid=$hotelId and parentTypeId=0");
        $parentTypesId = "";
        if($types){
            foreach ($types as $k => $v) {
                if ($k == 0) {
                    $parentTypesId.=$v['id'];
                } else {
                    $parentTypesId.="','" . $v['id'];
                }
            }
        }
        
        $sql = "select a.*,b.rebate,b.priceDate,b.priceEndDate,b.sellPrice,b.thDay from hotel_type as a";
		$sql.=" left join hotel_price as b on b.typeid=a.id and b.times=0";
        if($this->partnerInfo['isbusiness']==1){
        	$sql.=" where a.parentTypeId in('" . $parentTypesId . "') and a.categoryid=$hotelId";
			$sql.=" and zisort<=4 order by a.zisort asc";
        }elseif ($this->partnerInfo['isbusiness']==2){
        	$sql.=" where a.parentTypeId in('" . $parentTypesId . "') and a.categoryid=$hotelId and a.zisort!=3 and zisort!=4";
			$sql.=" and zisort!=7 and zisort!=8 order by a.zisort asc";
        }
       
        $parentTypes = $this->hotel->typeModel->fetchAll($sql);
        
        $channels=$this->pms->channelsModel->fetchAll("select a.osiiId,a.title from pms_channels as a left join pms_chstatus as b on b.chId=a.id where b.status=1 and b.hotelId=$hotelId");
        
        include $this->loadWidget('partnerTheme');
    }
	
	//查询房价
	function selectPrice(){
        $this->loadModel('hotel', 'price');
        $this->loadModel('hotel', 'type');
        $hotelId = $this->hotelziduan('id');
		$typeid=isset($_POST['typeid'])?(int)($_POST['typeid']):0;
		$parentTypeId=isset($_POST['parentTypeId'])?(int)($_POST['parentTypeId']):0;
		$sta=isset($_POST['sta'])?$_POST['sta']:'';
		$end=isset($_POST['end'])?$_POST['end']:'';
		$channelsId=isset($_POST['channelsId'])?$_POST['channelsId']:'';
		$where="";
		if($typeid){
			$where.=" and a.typeid=$typeid";
		}
		if($parentTypeId){
			$where.=" and a.parentTypeId=$parentTypeId";
		}
		if($sta){
			$where.=" and a.times>=".strtotime($sta);
		}
		if($end){
			$where.=" and a.times<=".strtotime($end);
		}
		if($channelsId){
			$where.=" and a.channels=$channelsId";
		}
		$typeName=$this->hotel->typeModel->fetchRow("select title from hotel_type where categoryid=$hotelId and id=$typeid");
		
		$sql="select a.times,a.sellPrice,a.created,b.title from hotel_price as a";
		$sql.=" left join pms_channels as b on b.osiiId=a.channels";
		$sql.=" where a.hotelId=$hotelId and a.isdetailed=1 and LOCATE(',',a.channels)<1".$where;
		$sql.=" and a.times>=".strtotime(date('Y-m-d',time()))." order by a.times,a.created asc";
		$re=$this->hotel->priceModel->fetchAll($sql);
		$html="";
		if($re){
			foreach($re as $k=>$v){
				$html.="<tr>";
					$html.="<td>".date('Y-m-d',$v['times'])."</td>";
					$html.="<td>".$v['sellPrice']."</td>";
					$html.="<td>".$v['title']."</td>";
					$html.="<td>".$v['created']."</td>";
				$html.="</tr>";
			}
		}else{
			$html="<tr><td colspan='4' style='text-align: center;'>无记录</td></tr>";
		}
		exit(json_encode(array('state'=>1,'html' => $html,'typeid' => $typeid,'parentTypeId' => $parentTypeId,'sta' => $sta,'end' => $end,'channelsId' => $channelsId,'typeName' => $typeName['title'])));
	}
	
    //修改房型价格
    function priceEdit() {
        global $pmsconfigs;
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/priceEdit");
        if(!$str_return){
        	ajaxReturn('', "没有该权限！", 0);exit;
        }
        $this->loadModel('hotel', 'price');
        $this->loadModel('hotel', 'type');
        $hotelId = $this->hotelziduan('id');

        $context = "";

        if ($_POST) {
            $parentTypeId = isset($_POST['parentTypeId']) ? (int) ($_POST['parentTypeId']) : 0; //父房型id
            $check = isset($_POST['check']) ? $_POST['check'] : ''; //选择推送的房型id
            $rebate = isset($_POST['rebate']) ? $_POST['rebate'] : ''; //折扣
            $staTime = isset($_POST['staTime']) ? $_POST['staTime'] : ''; //开始时间
            $endTime = isset($_POST['endTime']) ? $_POST['endTime'] : ''; //结束时间
            $thDay = isset($_POST['thDay']) ? $_POST['thDay'] : ''; //提前天数 连续天数
            $price = isset($_POST['price']) ? (int) ($_POST['price']) : ''; //房型挂牌价
            $channels = isset($_POST['channels']) ? $_POST['channels'] : ''; //渠道推送
			$breakfast = isset($_POST['breakfast']) ? $_POST['breakfast'] : ''; //早餐数
            if (!$check) {
                ajaxReturn('', '请选择要推送的类型！', 0);exit;
            }
            if(!$channels){
                ajaxReturn('', '请选择渠道！', 0);exit;
            }else{
                $channelsall="";
                foreach($channels as $k=>$v){
                    $channelsall.=','.$v;
                }
                $channelsall=trim($channelsall,',');
            }
            
            $data = array();
            $typearr = array();
            //开始时间判断
            if ($staTime) {
                foreach ($staTime as $k => $v) {
                    if (array_key_exists($k, $check) == false) {
                        unset($staTime[$k]);
                    } else {
                        if ($v) {
                            $data[$k]['priceDate'] = strtotime($v);
                        } else {
                            ajaxReturn('', '开始时间不能为空！', 0);exit;
                        }
                    }
                }
            }

            //结束时间判断
            if ($endTime) {
                foreach ($endTime as $k => $v) {
                    if (array_key_exists($k, $check) == false) {
                        unset($endTime[$k]);
                    } else {
                        if (!$v) {
                            ajaxReturn('', '结束时间不能为空！', 0);exit;
                        } else {
                            $data[$k]['priceEndDate'] = strtotime($v);
                        }
                    }
                }
            }

            //开始时间判断
            if ($rebate) {
                foreach ($rebate as $k => $v) {
                    if (array_key_exists($k, $check) == false) {
                        unset($rebate[$k]);
                    } else {
                        $data[$k]['rebate'] = $v;
                    }
                }
            }
            //房型名称修改数组
            if ($thDay) {
                foreach ($thDay as $k => $v) {
                    if (array_key_exists($k, $check) == false) {
                        unset($thDay[$k]);
                    } else {
                        $data[$k]['thDay'] = $v;
                        $typearr[$k]['thDay'] = $v;
                    }
                }
            }
			//早餐数
			if($breakfast){
				foreach($breakfast as $k=>$v){
					if (array_key_exists($k, $check) == false) {
                        unset($breakfast[$k]);
                    } else {
                        $data[$k]['breakfast']=$v;
                    }
				}
			}
			
            foreach ($data as $k => $v) {
                if ($v['priceEndDate'] - $v['priceDate'] < 0) {
                    ajaxReturn('', '结束时间不能小于开始时间！', 0);exit;
                }
                $data[$k]['parentTypeId'] = $parentTypeId;
                $data[$k]['sellPrice'] = 0;
                $zhekou = $pmsconfigs['zhekou'][$v['rebate']];
                $thprice = ceil($zhekou / 10 * $price);
                $data[$k]['sellPrice'] = $thprice;
            }
            
            //设置时间段的记录
            foreach ($data as $k => $v) {
                $isyes = $this->hotel->priceModel->fetchRow("select id from hotel_price where hotelId=$hotelId and typeid=$k and isdetailed=0");
                if ($isyes) {
                    $data[$k]['created']=date('Y-m-d H:i:s');
                    $re = $this->hotel->priceModel->update($data[$k], "hotelId=$hotelId and typeid=$k and id=" . $isyes['id']);
                } else {
                    $data[$k]['typeid'] = $k;
                    $data[$k]['hotelId'] = $hotelId;
                    $data[$k]['isdetailed']=0;
                    $re = $this->hotel->priceModel->insert($data[$k]);
                }
                $this->priceDay($v['priceDate'], $v['priceEndDate'], $k, $v['parentTypeId'], $hotelId, $v['sellPrice'],$channelsall);
            }
            //echo "<pre>";print_r($typearr);exit;
            if ($data) {
                $this->loadApi('osiiHotel');
                $osiiHotel = new osiiHotel();
                //设置OTA房型名称
                if ($typearr) {
                    foreach ($typearr as $k => $v) {
						$sql="select a.title,a.zisort,b.title as typeName from hotel_type as a left join hotel_type as b";
						$sql.=" on b.id=a.parentTypeId where a.id=$k and a.categoryid=$hotelId";
                        $name = $this->hotel->typeModel->fetchRow($sql);
						$namearr="";
						if($name&&$name['zisort']==3){
							$namearr['title']=$name['typeName']."(提前".$v['thDay']."天以上预订)";
						}elseif($name&&$name['zisort']==4){
							$namearr['title']=$name['typeName']."(连续".$v['thDay']."天以上入住)";
						}elseif($name&&$name['zisort']==7){
							$namearr['title']=$name['typeName']."(提前".$v['thDay']."天以上预订)(现付)";
						}elseif($name&&$name['zisort']==8){
							$namearr['title']=$name['typeName']."(连续".$v['thDay']."天以上入住)(现付)";
						}
                        $istype = $this->hotel->typeModel->update($namearr, "id=$k and categoryid=$hotelId");
                        if (!$istype) {
                            unset($typearr[$k]);
                        }
                    }
                }
				
                if ($typearr) {
                    $th = 0;
                    $bodys = array();
                    foreach ($typearr as $k => $v) {
                        $tharr = $this->hotel->typeModel->fetchRow("select * from hotel_type where categoryid=$hotelId and id=$k");
                        $bodys[$th]['hotelCode'] = $hotelId;
                        $bodys[$th]['roomTypeCode'] = $k;
                        $bodys[$th]['roomName'] = $tharr['title'];
                        $bodys[$th]['areaRange'] = $tharr['area'];
                        $bodys[$th]['floorRange'] = $tharr['floor'];
                        $bodys[$th]['roomDesc'] = "";
                        $bodys[$th]['person'] = $tharr['maxnumber'];
                        $bodys[$th]['addBed'] = 0;
                        $bodys[$th]['addBedFee'] = 0;
                        $bodys[$th]['roomQuantity'] = 0;
                        $bodys[$th]['currency'] = "RMB";
                        $bodys[$th]['noSmoking'] = 0;
                        $bodys[$th]['window'] = 0;
                        $bodys[$th]['children'] = 0;
                        $bodys[$th]['hasBroadNet'] = "";
                        $bodys[$th]['hasWirelessBroadnet'] = "";
                        $bodys[$th]['wiredBroadnetRoom'] = 0;
                        $bodys[$th]['wirelessBroadnetRoom'] = 0;
                        $bodys[$th]['bedTypeID'] = 0;
                        $bodys[$th]['bedTypeName'] = $tharr['bed'];
                        $th++;
                    }
                    $reosii_a = $osiiHotel->types($bodys);
                }
                //设置OTA 价格
                $this->toOsiiPrice($data,$channels);
                ajaxReturn('refurbish', '操作成功！', 1);exit;
            }
            ajaxReturn('', '操作失败！', 0);exit;
        }
    }
    /**
     * 价格推送
     */
    function toOsiiPrice($data,$channels){
        $this->loadApi('osiiHotel');
        $osiiHotel = new osiiHotel();
        
        $hotelId=$this->hotelziduan('id');
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'typestatus');
        $this->loadModel('sys', 'setprice');
        $this->loadModel('float','log');
		$this->loadModel('pms','account');
        
        $dataAll=array();
        $ka=$kk=0;
        foreach($channels as $k=>$v){
            foreach($data as $key=>$val){
                $dataAll[$ka]['channels']=$v;
                $dataAll[$ka]['priceDate']=$val['priceDate'];
                $dataAll[$ka]['priceEndDate']=$val['priceEndDate'];
                $dataAll[$ka]['parentTypeId']=$val['parentTypeId'];
                $dataAll[$ka]['sellPrice']=$val['sellPrice'];
                $dataAll[$ka]['breakfast']=isset($val['breakfast'])?$val['breakfast']:0;
                $dataAll[$ka]['typeId']=$key;
                $ka++;
            }
        }
        //echo "<pre>";print_r($dataAll);exit;
        foreach ($dataAll as $k => $v) {
            $body = array('setRoomPriceItems' => array());
            $iday = ($v['priceEndDate'] - $v['priceDate']) / 24 / 3600;
            $body['setRoomPriceItems'][$kk]['priceInfos'] = array();
            $body['setRoomPriceItems'][$kk]['hotelId'] = $hotelId;
            $body['setRoomPriceItems'][$kk]['roomId'] = $v['typeId'];
            $body['setRoomPriceItems'][$kk]['startDate'] = date('Y-m-d', $v['priceDate']) . 'T00:00:00';
            $body['setRoomPriceItems'][$kk]['endDate'] = date('Y-m-d', $v['priceEndDate']) . 'T00:00:00';
            $body['setRoomPriceItems'][$kk]['currency'] = "CNY";
            $body['setRoomPriceItems'][$kk]['sourceId'] = $v['channels'];
            for ($i = 0; $i <= $iday; $i++) {
                
                $times=$v['priceDate']+$i*24*3600;
                $price=$v['sellPrice'];
                
                $sql_a="select setprice,fudong from sys_setprice where hotelId=$hotelId and typeId=".$v['typeId']." and parentTypeId=".$v['parentTypeId'];
                $sql_a.=" and times=$times and channelsId=".$v['channels'];
                $setprice=$this->sys->setpriceModel->fetchRow($sql_a);
                if($setprice){
                    $price=$setprice['fudong']==1?$price+$setprice['setprice']:$price-$setprice['setprice'];
                }
                
                $sql_b="select floating,sellmoney from float_log where hotelid=$hotelId and parent_TypeId=".$v['parentTypeId'];
                $sql_b.=" and time=$times";
                $floatprice=$this->float->logModel->fetchRow($sql_b);
                if($floatprice){
                    $price=$floatprice['floating']==1?$price+$floatprice['sellmoney']:$price-$floatprice['sellmoney'];
                }
                
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['prices'] = array();
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['prices'][0]['amountBeforeTaxFee'] = $price;
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['prices'][0]['amountAfterTaxFee'] = $price;
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['prices'][0]['costAmountBeforeTaxFee'] = $price;
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['prices'][0]['costAmountAfterTaxFee'] = $price;
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['prices'][0]['day'] = 0;
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['stays'] = 0;
                
                $blanceType=$this->hotel->typestatusModel->fetchRow("select payType from hotel_typestatus where hotelId=$hotelId and typeId=".$v['typeId']." and times=$times");
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['blanceType'] = $blanceType&&$blanceType['payType']!=''?$blanceType['payType']:"PP";
                
                $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['priceType'] = $blanceType&&$blanceType['payType']=='FG'?"Sell":"Cost";
                $sort_th = $this->hotel->typeModel->fetchRow("select zisort from hotel_type where id=".$v['typeId']);
                if ($sort_th && ($sort_th['zisort'] == 1 || $sort_th['zisort'] == 5)) {
                    $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['breakfast'] = $v['breakfast'];
                } else {
                    $body['setRoomPriceItems'][$kk]['priceInfos'][$i]['breakfast'] = 0;
                }
				$isbusiness=$this->pms->accountModel->fetchRow("select a.isbusiness from pms_account as a left join hotel_category as b on b.partnerid=a.id where b.id=$hotelId");
				if($isbusiness['isbusiness']==1){
					$body['setRoomPriceItems'][$kk]['priceInfos'][$i]['isCancel'] = 0;
				}else{
					$body['setRoomPriceItems'][$kk]['priceInfos'][$i]['isCancel'] = 1;
				}
			}
            //echo json_encode($body)."\r\n\r\n";
            $reosii = $osiiHotel->typePrice($body);
        }
    }
    
    /**
     * 循环录入每天价格
     * @param type $statime 开始时间
     * @param type $endtime 结束时间
     * @param type $parent 父级ID
     * @param type $hotelid 酒店ID
     * @param type $price 价格
     */
    function priceDay($statime,$endtime,$typeid,$parent,$hotelid,$price,$channelsall){
        $this->loadModel('hotel', 'price');
        $this->loadModel('sys', 'setprice');
        $this->loadModel('float','log');
        $data['sellPrice']=$price;
        $data['created']=date('Y-m-d H:i:s',time());
        $channelsall=explode(',',$channelsall);
        if (!empty($endtime) && (($endtime - $statime) / 24 / 3600) > 0) {
            $day = ($endtime - $statime) / 24 / 3600;
            for ($i = 0; $i <= $day; $i++) {
                foreach($channelsall as $k=>$v){
                    $data['channels']=$v;
                    $times = $statime + $i * 24 * 3600;
                    $sql="select id from hotel_price where isdetailed=1 and parentTypeId='".$parent."' and hotelId='".$hotelid."'";
                    $sql.=" and typeid='".$typeid."' and times='".$times."' and channels='".$v."'";
                    $priceArr = $this->hotel->priceModel->fetchRow($sql);
                    if(!empty($priceArr)){
                        $this->hotel->priceModel->update($data,'id='.$priceArr['id']);
                        
                        $this->setLogs("价格录入：".json_encode(array('sellPrice'=>$price,'hotelid'=>$hotelid,'typeid'=>$typeid,'parentTypeId'=>$parent,'times'=>date('Y-m-d',$times),'channels'=>$v)));
                    }else{
                        $arr = array(
                            'times'=>$times,
                            'typeid'=>$typeid,
                            'parentTypeId'=>$parent,
                            'hotelId'=>$hotelid,
                            'sellPrice'=>$price,
                            'isdetailed'=>1,
                            'channels'=>$v
                        );
                        $this->hotel->priceModel->insert($arr);
                        
                        $this->setLogs("价格录入：".json_encode($arr));
                    }
                }
            }
        }else{
            foreach($channelsall as $k=>$v){
                $sql="select id from hotel_price where isdetailed=1 and parentTypeId='".$parent."' and hotelId='".$hotelid."'";
                $sql.=" and typeid='".$typeid."' and times='".$statime."' and channels='".$v."'";
                $priceArr = $this->hotel->priceModel->fetchRow($sql);
                if(!empty($priceArr)){
                    $this->hotel->priceModel->update($data,'id='.$priceArr['id']);
                    
                    $this->setLogs("价格录入：".json_encode(array('sellPrice'=>$price,'hotelid'=>$hotelid,'typeid'=>$typeid,'parentTypeId'=>$parent,'times'=>date('Y-m-d',$statime),'channels'=>$v)));
                }else{
                    $arr = array(
                        'times'=>$statime,
                        'typeid'=>$typeid,
                        'parentTypeId'=>$parent,
                        'hotelId'=>$hotelid,
                        'sellPrice'=>$price,
                        'isdetailed'=>1,
                        'channels'=>$v
                    );
                    $this->hotel->priceModel->insert($arr);
                    
                    $this->setLogs("价格录入：".json_encode($arr));
                }
            }
        }
        
        $this->loadModel('hotel','category');
        $this->loadModel('hotel','type');
        $this->loadModel('pms','channels');
        $channelsName="";$content="系统通知：";
        $hotelName=$this->hotel->categoryModel->fetchRow("select hotelName from hotel_category where id=$hotelid");
        $typeName=$this->hotel->typeModel->fetchRow("select title from hotel_type where id=$typeid and parentTypeId=$parent");
        foreach($channelsall as $k=>$v){
            $re=$this->pms->channelsModel->fetchRow("select title from pms_channels where osiiId=$v");
            if($re){
                $channelsName.=$re['title'].'、';
            }
        }
        $content.=$hotelName['hotelName'].'----'.$typeName['title'].'----'.date('Y-m-d',$statime).' 到 '.date('Y-m-d',$endtime).'----'.$price.'元'.'----渠道：'.$channelsName.'，价格变动，请注意查看！';
        
        //$this->get_th_all("18113011002,18782978101",$content);
    }
    /**
     * 短信接口
     */
    function post_sms($curlPost,$url){
        $curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
    }
    function get_th_all($mobile="13548078020",$content=""){
        $this->loadModel('message','log');
        $url="http://106.ihuyi.cn/webservice/sms.php?method=Submit&format=json";
        $yzm=substr(uniqid(rand()),-6);
        $password=md5('lzp30000');
        
        $mobileAll=array();
        $mobileAll=explode(',',trim($mobile,','));
        
        if(is_array($mobileAll)){
            foreach($mobileAll as $k=>$v){
                $curlPost="account=cf_hundun&password=".$password."&mobile=".$v."&content=".rawurlencode($content);
                $return=$this->post_sms($curlPost,$url);
                $data['content']="手机号：".$v."，内容：".$content."，返回码：".addslashes($return);
                $data['status']="发送失败";
                $return=json_decode($return);
                if($return->code=='2'){
                    $data['status']="发送成功";
                }
                $this->message->logModel->insert($data);
            }
        }
    }
    
    //价格浮动
    function priceupdate() {
        $leftpost = "hotel";
        $leftbot = "price";
        $this->loadHelper('extend');
        $this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("hotel/priceupdate");
        if(!$str_return){
            $js->alert("您没有该权限！");exit();
        }
        global $pmsconfigs;
        $this->loadModel('hotel', 'type');
        $this->loadModel('hotel', 'price');
        $hotelId = $this->hotelziduan('id');

        $types = $this->hotel->typeModel->fetchAll("select * from hotel_type where status=1 and categoryid=$hotelId and parentTypeId=0");

        //echo "<pre>";print_r($types);exit;

        include $this->loadWidget('partnerTheme');
    }

    function boxShow() {
        $this->loadModel('hotel', 'type');
        if ($_POST) {
            $typeids = $_POST['typeid'];
            $db = $this->hotel->typeModel->fetchAll("select id,title from hotel_type where id in (" . $typeids . ")");
            exit(json_encode($db));
        }
    }
    
    //浮动价格修改
    function datetime() {
    	$this->loadHelper('extend');
        $str_return = $this->my_authority("hotel/datetime");
        if(!$str_return){
        	ajaxReturn('', "没有该权限！", 0);exit;
        }
        
        $sta = isset($_POST['statime'])?strtotime($_POST['statime']):'';
        $end = isset($_POST['statime'])?strtotime($_POST['endtime']):'';
        $box=isset($_POST['box'])?$_POST['box']:'';
        
        $money=isset($_POST['money'])?$_POST['money']:'';
        $floating=isset($_POST['floating'])?$_POST['floating']:'';
        
        $parentTypeId=isset($_POST['parentTypeId'])?(int)($_POST['parentTypeId']):0;
        $typeidArr=isset($_POST['typeid'])?$_POST['typeid']:'';
        $typeidsArr=isset($_POST['typeids'])?$_POST['typeids']:'';
        
        if(trim($money)==''){
            ajaxReturn('', '请输入浮动金额！', 0);exit;
        }/*elseif($money&&is_array($money)&&in_array('',$money)){
            ajaxReturn('', '请输入浮动金额！', 0);exit;
        }*/
        
        if(!$sta||!$end){
            ajaxReturn('', '请选择时间段！', 0);exit;
        }elseif($end<$sta){
            ajaxReturn('', '请选择正确的时间段！', 0);exit;
        }
        
        if(!$box){
            ajaxReturn('', '请选择星期！', 0);exit;
        }
        
        if($parentTypeId){//单房型浮动
            $this->oneFloating($parentTypeId,$floating,$money,$sta,$end,$box);
        }/*elseif(!$parentTypeId&&$typeidsArr){//多房型不同价浮动
            $this->diverseFloating();
        }elseif(!$parentTypeId&&!$typeidsArr){//多房型相同价浮动
            $this->equalFloating($typeidArr,$floating,$money,$sta,$end,$box);
        }*/
        ajaxReturn('', '操作成功！', 1);exit;
    }
    /**
     * 单房型浮动
     * @$parentTypeId  父房型id        @$floating  1加浮，2减浮      @$money  浮动金额
     * @$sta  浮动开始时间        @$end  浮动结束时间       @$box  浮动星期数组
     */
    function oneFloating($parentTypeId,$floating,$money,$sta,$end,$box){
        $hotelId = $this->hotelziduan('id');
    	$this->loadHelper('extend');
        $this->loadModel('hotel', 'price');
        $this->loadModel('float', 'log');
        
        $money=(int)($money);
        $day=($end-$sta)/24/3600;
        $arr=$typePriceArr=$priceAll=array();
        for($i=0;$i<=$day;$i++){
            $times=$sta+$i*24*3600;
            foreach($box as $k=>$v){
                if(intval(date('w',$times))==$v){
                    $arr[$i]=$times;
                }
            }
        }
        if($arr){
            $data['hotelid']=$hotelId;
            $data['parent_TypeId']=$parentTypeId;
            $data['floating']=$floating;
            $data['sellmoney']=$money;
            $data['createtime']=date('Y-m-d H:i:s',time());
            foreach($arr as $k=>$v){
				$data['time']=$v;
                $re=$this->float->logModel->fetchRow("select id from float_log where hotelid=$hotelId and parent_TypeId=$parentTypeId and time=$v");
                if($re){
                    $this->float->logModel->update($data,"id=".$re['id']);
                }else{
                    $this->float->logModel->insert($data);
                }
				$this->setLogs("酒店浮动价格：".json_encode($data));
                $sql="select typeid,parentTypeId,hotelId,times,sellPrice,channels from hotel_price where hotelId=$hotelId";
                $sql.=" and parentTypeId=$parentTypeId and times=$v and isdetailed=1";
                $prices=$this->hotel->priceModel->fetchAll($sql);
                if($prices){
                    $typePriceArr[$k]=$prices;
                }
            }
        }
        $kk=0;
        if($typePriceArr){
            foreach($typePriceArr as $k=>$v){
                foreach($v as $key=>$val){
                    if(is_numeric($val['channels'])){
                        $priceAll[$kk]=$val;
                        $priceAll[$kk]['floating']=$floating;
                        $priceAll[$kk]['money']=$money;
                        $kk++;
                    }
                }
            }
        }
        if($priceAll){
            $this->tuoOsii($priceAll);
        }
    }
    /**
     * 多房型 相同价格浮动
     * @$typeidArr  父房型数组       @$floating  1加浮 2减浮     @$money  加减浮金额
     * @$sta  浮动开始时间        @$end  浮动结束时间       @$box  浮动星期数组
     */
    /*function equalFloating($typeidArr,$floating,$money,$sta,$end,$box){
        $hotelId = $this->hotelziduan('id');
    	$this->loadHelper('extend');
        $this->loadModel('hotel', 'price');
        $this->loadModel('float', 'log');
        
        $money=(int)($money);
        if($money<1){
            ajaxReturn('', '操作失败，金额不能小于0！', 0);exit;
        }
    }
    /**
     * 多房型 不同价格浮动
     */
    /*function diverseFloating(){
        
    }*/
    
    /**
     * 浮动价格变动  推送osii
     * @$data  房型价格渠道一维数组
     */
    function tuoOsii($data){
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','typestatus');
        $this->loadModel('sys','setprice');
		$this->loadModel('pms','account');
        $this->loadModel('hotel','price');
        
        $this->loadApi('osiiHotel');
        $osiiHotel = new osiiHotel();
        
        $kk=0;
        foreach($data as $k=>$v){
            $body = array('setRoomPriceItems' => array());
            $body['setRoomPriceItems'][$kk]['priceInfos'] = array();
            $body['setRoomPriceItems'][$kk]['hotelId'] = $v['hotelId'];
            $body['setRoomPriceItems'][$kk]['roomId'] = $v['typeid'];
            $body['setRoomPriceItems'][$kk]['startDate'] = date('Y-m-d', $v['times']) . 'T00:00:00';
            $body['setRoomPriceItems'][$kk]['endDate'] = date('Y-m-d', $v['times']) . 'T00:00:00';
            $body['setRoomPriceItems'][$kk]['currency'] = "CNY";
            $body['setRoomPriceItems'][$kk]['sourceId'] = $v['channels'];
            
            $price=$v['floating']==1?$v['sellPrice']+$v['money']:$v['sellPrice']-$v['money'];
            
            $sql="select setprice,fudong from sys_setprice where hotelId=".$v['hotelId']." and typeId=".$v['typeid']." and parentTypeId=".$v['parentTypeId'];
            $sql.=" and times=".$v['times']." and channelsId=".$v['channels'];
            $setprice=$this->sys->setpriceModel->fetchRow($sql);
            if($setprice){
                $price=$setprice['fudong']==1?$price+$setprice['setprice']:$price-$setprice['setprice'];
            }
            
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['prices'] = array();
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['prices'][0]['amountBeforeTaxFee'] = $price;
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['prices'][0]['amountAfterTaxFee'] = $price;
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['prices'][0]['costAmountBeforeTaxFee'] = $price;
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['prices'][0]['costAmountAfterTaxFee'] = $price;
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['prices'][0]['day'] = 0;
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['stays'] = 0;
            
            $blanceType=$this->hotel->typestatusModel->fetchRow("select payType from hotel_typestatus where hotelId=".$v['hotelId']." and typeId=".$v['typeid']." and times=".$v['times']);
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['blanceType'] = $blanceType&&$blanceType['payType']!=''?$blanceType['payType']:"PP";
            $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['priceType'] = $blanceType&&$blanceType['payType']=='FG'?"Sell":"Cost";
			
			//查询早餐数
			$breKpriceSql="select breakfast from hotel_price where hotelId=".$v['hotelId']." and typeid=".$v['typeid']." and isdetailed=0";
			$breKprice=$this->hotel->priceModel->fetchRow($breKpriceSql);
            $sort_th = $this->hotel->typeModel->fetchRow("select zisort from hotel_type where id=".$v['typeid']);
            if ($sort_th && ($sort_th['zisort'] == 1||$sort_th['zisort']==5)) {
                $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['breakfast'] = $breKprice['breakfast']?$breKprice['breakfast']:1;
            } else {
                $body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['breakfast'] = 0;
            }
			
			//查询是否包房商设置可否取消
			$isbusinessSql="select a.isbusiness from pms_account as a left join hotel_category as b on b.partnerid=a.id where b.id=".$v['hotelId'];
			$isbusiness=$this->pms->accountModel->fetchRow($isbusinessSql);
			if($isbusiness['isbusiness']==1){
				$body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['isCancel'] = 0;
			}else{
				$body['setRoomPriceItems'][$kk]['priceInfos'][$kk]['isCancel'] = 1;
			}
			
            $reosii = $osiiHotel->typePrice($body);
        }
    }
	
    //操作日志
    function floatlog() {
    	$this->loadModel('float', 'log');
    	$hotelId = $this->hotelziduan('id');
        $parent_TypeId=isset($_POST['parent_TypeId'])?(int)($_POST['parent_TypeId']):0;
        $sta=isset($_POST['sta'])?$_POST['sta']:0;
        $end=isset($_POST['end'])?$_POST['end']:0;
		
		$where="";
		if($sta){
			$where.=" and time>=".strtotime($sta);
		}
		if($end){
			$where.=" and time<=".strtotime($end);
		}
		$sql="select time,sellmoney,floating,createtime from float_log where hotelid=$hotelId and parent_TypeId=$parent_TypeId";
		$sql.=$where." and time>=".strtotime(date('Y-m-d',time()))." order by time asc";
		$re=$this->float->logModel->fetchAll($sql);
		$html="";
		if($re){
			foreach($re as $k=>$v){
				$html.="<tr>";
					$html.="<td>".date('Y-m-d',$v['time'])."</td>";
					$html.="<td>".($v['floating']==1?"加浮":"减浮")."</td>";
					$html.="<td>".$v['sellmoney']."</td>";
					$html.="<td>".$v['createtime']."</td>";
				$html.="</tr>";
			}
		}else{
			$html="<tr><td colspan='4' style='text-align: center;'>无记录</td></tr>";
		}
		exit(json_encode(array('state'=>1,'html' => $html,'parent_TypeId' => $parent_TypeId,'sta' => $sta,'end' => $end)));
    }

}
